var http = require('http');
var fs = require('fs');
// var util = require('util');

var server = http.createServer(function(req, res) {


    // https://blog.csdn.net/rocky0503/article/details/72903359
    if (req.url == '/favicon.ico') res.end();

    // 如果为/, 默认访问index.html页面
    if (req.url == '/') {
        fs.readFile("./index.html", "utf-8", function(err, data) {
            if (!err) {
                res.end(data);
            } else {
                res.end('网页异常');
            }
        });

    }
    console.log(req.url);
    var path = req.url.replace('/', '');

    // 如果请求的是css文件
    var reg = /\.css$/;
    if (reg.test(req.url)) {
        fs.readFile(path, "utf-8", function(err, data) {
            if (!err) {
                res.writeHead(200, {
                    'Content-Type': 'text/css;charset=utf-8'
                });

                res.end(data);
            } else {
                res.end('404 NOT FOUNT');
            }
        });
    } else {
        fs.readFile('./html/' + path + '.html', "utf-8", function(err, data) {
            if (!err) {
                res.writeHead(200, {
                    'Content-Type': 'text/html;charset=utf-8'
                });
                res.end(data);
            } else {
                res.end('404 NOT FOUNT');
            }
        });
    }

});

server.listen(8080, function(err) {
    if (!err) {
        console.log("服务器已经运行: 端口号是: 8080");
    }
});

